<template>
  <div>
    <el-dialog
        v-model="visible"
        top="6vh"
        width="680px"
        :show-close="false"
        :close-on-click-modal="false"
        :title="title"
        :before-close="handleClose"
        class="staff-operate-dialog"
    >
      <el-form
          ref="StaffFormRef"
          :rules="rules"
          :model="staffFrom"
          v-loading="loading"
          class="staff-form">
        <div>
          <!-- 员工头像 -->
          <el-form-item>
            <img :src="staffFrom.avatarUrl" style="line-height: 1.42857143;
              background-color: #fff;
              border: 1px solid #ddd;
              border-radius: 4px;
              height: 110px;
              width: 110px;padding: 4px;">
          </el-form-item>
            <!--  重置密碼 的按鈕         -->
            <el-button v-if="staff && staff.id" class="w-full" type="primary" :loading="resetPasswordLoading" @click="resetPasswordHandler">{{ $t('loc.retPwd') }}</el-button>
        </div>
        <div>
          <div class="flex-row">
            <el-form-item style="width: 90px;">
              <el-select v-model="staffFrom.prefix">
                <el-option
                    v-for="item in prefixOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="lastName" class="first-name-item" required>
              <el-input :placeholder="$t('loc.lastName')" v-model="staffFrom.lastName" type="text" autocomplete="off"/>
            </el-form-item>
          </div>
          <el-form-item prop="firstName" :label="$t('loc.1stName')" required>
            <el-input :placeholder="$t('loc.1stName')" v-model="staffFrom.firstName" type="text" autocomplete="off"/>
          </el-form-item>
          <el-form-item prop="firstName" :label="$t('loc.email')" required>
            <el-input :placeholder="$t('loc.email')" v-model="staffFrom.email" type="text" autocomplete="off"/>
          </el-form-item>
          <el-form-item prop="role" :label="$t('loc.role')" required>
            <el-select v-model="staffFrom.role" :placeholder="$t('loc.role')" style="width: 100%;">
              <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <div v-if="staffFrom.role === 'AGENCY_ADMIN'">
            {{ $t('loc.accAllSite') }}
          </div>
          <div v-if="staffFrom.role === 'SCHOOL_ADMIN'">
            <el-form-item prop="schoolIds" :label="'管理范围'" required>
              <el-select
                  v-model="staffFrom.schoolIds"
                  multiple
                  :placeholder="$t('loc.selCenter')"
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in schoolOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div v-if="staffFrom.role === 'TEACHER'">
            <el-form-item prop="groupIds" :label="'管理范围'" required>
              <el-select v-model="staffFrom.groupIds"
                         multiple
                         :placeholder="$t('loc.choseGp')"
                         style="width: 100%;">
                <el-option-group
                    v-for="school in schoolGroupOptions"
                    :key="school.id"
                    :label="$t('loc.center') + ': ' + school.name"
                >
                  <el-option
                      v-for="item in school.groups"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer flex-align-justify">
          <el-button :loading="submitLoading" type="danger" @click="deleteHandler">删除</el-button>
        <div>
          <el-button @click="handleClose">{{ $t('loc.cancel') }}</el-button>
          <el-button :loading="submitLoading" type="primary" @click="submitHandler">
             {{ $t('loc.submit') }}
          </el-button>
        </div>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {VideoCamera} from "@element-plus/icons-vue";
import UserApi from "@/api/user";
import ChildApi from '@/api/child'
import {validateEMail} from "@/utils/rules";

export default {
  name: "AddStaffDialog",
  components: {VideoCamera},
  props: ['dialogVisible', 'staff'],
  data() {
    let emailValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      }
      if (!validateEMail(value)) {
        callback(new Error(this.$t('loc.InvEmailAddress')));
      }
      callback();
    };
    return {
      visible: false,
      loading: false,
      submitLoading: false,
      setSchoolsAndGroupsLoading: false,
      resetPasswordLoading: false,
      staffFrom: {
        prefix: '',
        avatarUrl: 'https://d2urtjxi3o4r5s.cloudfront.net/images/user_avatar_2020.png?v=1',
        lastName: '',
        firstName: '',
        email: '',
        role: '',
        schoolIds: [],
        groupIds: [],
      },
      prefixOptions: [
        {
          value: '',
          label: this.$t('loc.noPrefix'),
        },
        {
          value: 'Mr',
          label: this.$t('loc.Mr'),
        },
        {
          value: 'Miss',
          label: this.$t('loc.Miss'),
        },
      ],
      roleOptions: [
        {
          value: 'AGENCY_ADMIN',
          label: this.$t('loc.agencyAdmin'),
        },
        {
          value: 'SCHOOL_ADMIN',
          label: this.$t('loc.siteAdmin'),
        },
        {
          value: 'TEACHER',
          label: this.$t('loc.teacherRole'),
        },
      ],
      schools: [],
      rules: {
        email: [
          {required: true, validator: emailValidator,  trigger: 'blur'},
        ],
      },
      needReLoadData: false,
    }
  },
  watch: {
    dialogVisible: function (val) {
      this.visible = val;
      if (val) {
        this.initData()
      }
      this.clearFormValidate();
    }
  },
  computed: {
    title() {
      return (this.staff && this.staff.id) ? '编辑老师' : this.$t('loc.addStf');
    },
    schoolOptions() {
      return this.schools;
    },
    schoolGroupOptions () {
      // 将幼儿园中的不活跃班级过滤掉
      return this.schools.map(school => {
        const groups = school.groups.filter(group => group.isInactive !== true)
        return {
          id: school.id,
          name: school.name,
          groups: groups
        }
      })
    }
  },
  methods: {
    clearFormValidate() {
      this.$nextTick(() => {
        this.$refs.StaffFormRef.clearValidate();
      });
    },
    initData() {
      this.loadStaffInfo();
      this.loadSetSchoolsAndGroups();
    },
    loadStaffInfo() {
      if (this.staff && this.staff.id) {
        let staff = this.staff
        // prefix 从 displayName 中解析
        let prefix = staff.displayName.split(' ')[0]
        if (prefix === staff.lastName) {
           prefix = ''
        }
        this.staffFrom = {
          prefix: prefix,
          avatarUrl: 'https://d2urtjxi3o4r5s.cloudfront.net/images/user_avatar_2020.png?v=1',
          lastName: staff.lastName,
          firstName: staff.firstName,
          email: staff.email,
          role: staff.role,
        }
      } else {
        this.staffFrom = {}
        this.staffFrom.avatarUrl = 'https://d2urtjxi3o4r5s.cloudfront.net/images/user_avatar_2020.png?v=1'
      }
      this.clearFormValidate();
    },
    loadSetSchoolsAndGroups() {
      this.setSchoolsAndGroupsLoading = true
      ChildApi.getSetSchoolAndGroup(this.childId).then(res => {
        this.schools = res
        // 如果是编辑，需要将幼儿园和班级的id设置到staffFrom中
        if (this.staff && this.staff.id) {
          let schoolIds = this.staff.schools.map(school => school.id) || []
          let groupIds = this.staff.schools.flatMap(school => school.groups).map(group => group.id)
          // 去重
          schoolIds = [...new Set(schoolIds)]
          groupIds = [...new Set(groupIds)]
          this.staffFrom.schoolIds = schoolIds
          this.staffFrom.groupIds = groupIds
          console.log('this.staffFrom', this.staffFrom.groupIds)
        }
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.setSchoolsAndGroupsLoading = false
      })
    },
    handleClose() {
      this.visible = false
      this.$emit('update:dialogVisible', this.visible)
      if (this.needReLoadData === true) {
        this.$emit('needReLoadData')
        this.needReLoadData = false
      }
    },
    deleteHandler () {
      this.$confirm(this.$t('loc.relieveTea', {teacherName: this.staff.userName}), this.$t('loc.tip'), {
        confirmButtonText: this.$t('loc.done'),
        cancelButtonText: this.$t('loc.cancel'),
        type: 'warning',
      }).then(() => {
        this.submitLoading = true
        UserApi.deleteStaff(this.staff.id).then(() => {
          this.submitLoading = false
          this.needReLoadData = true
          this.handleClose()
        })
      }).catch(() => {
        this.submitLoading = false
        this.$message.error(error.response.data.description)
      });
    },
    submitHandler() {
      // 校验
      this.$refs['StaffFormRef'].validate((valid) => {
        if (valid) {
          let param = {
            prefix: this.staffFrom.prefix,
            avatarMediaId: '',
            lastName: this.staffFrom.lastName,
            firstName: this.staffFrom.firstName,
            email: this.staffFrom.email,
            role: this.staffFrom.role,
            schoolIds: this.staffFrom.schoolIds,
            groupIds: this.staffFrom.groupIds,
          };
          if (this.staff && this.staff.id) {
            param.id = this.staff.id
            this.submitLoading = true
            UserApi.updateStaff(param).then(res => {
              this.$message.success(this.$t('loc.editStaffSucc'));
              this.needReLoadData = true;
              this.handleClose();
            }).catch(error => {
              this.$message.error(error.response.data.description)
            }).finally(() => {
              this.submitLoading = false;
            })
          } else {
            this.submitLoading = false;
            UserApi.createStaff(param).then(res => {
              this.$message.success(this.$t('loc.addStaffSucc'));
              this.needReLoadData = true;
              this.handleClose();
            }).catch(error => {
              this.$message.error(error.response.data.description)
            }).finally(() => {
              this.submitLoading = false;
            })
          }

        }
      });

    },
    resetPasswordHandler () {
      if (!this.staff || !this.staff.id) {
        return
      }
      this.$confirm(this.$t('loc.cfmRetPwd'), this.$t('loc.tip'), {
        confirmButtonText: this.$t('loc.done'),
        cancelButtonText: this.$t('loc.cancel'),
        type: 'warning',
      }).then(() => {
        this.resetPasswordLoading = true
        UserApi.resetPassword(this.staff.id, null).then(() => {
          this.resetPasswordLoading = false
          this.$message.success(this.$t('loc.pwdRstSfy'))
        }).catch(error => {
          this.resetPasswordLoading = false
          this.$message.error(error.response.data.description)
        })
      }).catch(() => {
        this.resetPasswordLoading = false
      });
    },
  },
}
</script>

<style scoped lang="less">
.staff-form {
  display: flex;
  justify-content: space-evenly;

}

.flex-row {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}


.first-name-item {
  /deep/ .el-form-item__content {
    margin-left: 5px !important;
  }
}

/deep/ .el-dialog__footer {
  border-top: 1px solid #e5e5e5;
  padding: 20px;
}

/deep/ .el-dialog {
  box-shadow: 0 5px 15px rgba(0,0,0,.5);
  border: 1px solid rgba(0,0,0,.2);
  border-radius: 6px;
  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;
    .el-dialog__title {
      font-size: 24px;
      color: #58666e;
    }
  }
}
.staff-operate-dialog /deep/{
  .input-label {
    margin-top: 10px;
    margin-bottom: 5px;
    color: #323338!important;
    font-size: 16px!important;
    font-weight: 400;
  }
}

</style>